<?php

namespace app\common\model;

use think\Cache;
use think\Db;
use think\Model;

/**
 * 领料申请单数据模型
 */
class Material extends Model
{
     public static function getList(){
          $field = 'b.id,b.auto_id,b.row_id,b.material_code pcode,a.order_date pdate,a.cdepcode,a.cdepname,
b.quantity,b.commit_quantity,b.warehouse_id,ifnull(b.tj_shelves_id,0) tj_shelves_id,ifnull(e.name,"") tj_shelves_name,b.cWhcode warehouse_code,d.name warehouse_name,
b.inventory_number inv_number,c.name inv_name,ifnull(specification,"")inv_specification ,
ifnull(c.attributes,"") inv_attributes,c.unit_code unit_code,c.unit unit_name,
case a.source when a.source=1 then "MES" else "KIS" end as source ,
ifnull(a.fitemssname,"") fitemssname,ifnull(a.cUser_Id,"") cUser_Id,ifnull(a.cUser_Name,"") cUser_Name,
ifnull(a.remark,"") remark'; 
          $data = self::field($field)->alias('a')
         ->join('material_list b','a.material_code=b.material_code')
         ->join('inventory c','c.number=b.inventory_number')
         ->join('warehouse d','d.id=b.warehouse_id','left')
         ->join('shelves e','e.id=b.tj_shelves_id','left')
         ->where([
             'a.status' => 1, //审核通过
             'b.status' => 1 //未关闭
         ])
         ->order('b.material_code desc,b.row_id')
         ->group('b.id')
         ->select();
          
         
         //$data = self::dealData($data);
         return $data;
     }

    /**
     * 按要求处理数据   poorder、poorder_item
     * @param $data
     * @return array
     */
    public static function dealData($data){
        $item  = $data;
        $poorder = array();
        foreach ($data as $k=>$v){
            if(!isset($poorder[$v['material_code']])){
                $poorder[$v['material_code']] = [
                    'material_code'=>$v['material_code'],
                    'inventory_number' => $v['inventory_number'],
                    'quantity' => $v['quantity'],
                ];
            }else{
                $poorder[$v['material_code']] = [
                    'material_code'=>$v['material_code'],
                    'inventory_number' => $poorder[$v['material_code']]['inventory_number'],
                    'quantity' => $poorder[$v['material_code']]['quantity']+$v['quantity'],
                ];
            }
        }

        return ['poorder'=>array_values($poorder),'item'=>$item];
    }
}
